package com.etc.order.frontend.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.etc.order.common.domain.User;
import com.etc.order.common.dto.SimpleDTO;
import com.etc.order.common.service.UserService;
import com.etc.order.frontend.filter.AuthFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
public class LoginController {
    @Resource
    @Reference
    private UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public SimpleDTO login(String username, String password) {
        if (userService.login(username, password)) {
            User user = userService.findByUsername(username);
            AuthFilter.getSession().setAttribute("userInfoFrontend", user);
            return new SimpleDTO(0, "成功", null);
        }
        return new SimpleDTO(1, "用户名或密码不正确", null);
    }

    @GetMapping("/currentUser")
    @ResponseBody
    public SimpleDTO getCurrentUser() {
        User user = (User) AuthFilter.getSession().getAttribute("userInfoFrontend");
        if (user != null) {
            return new SimpleDTO(0, "成功", user.getUserName());
        }
        return new SimpleDTO(1, "请先登录", null);
    }

    @GetMapping("/currentUser/address")
    @ResponseBody
    public String getUserAddress() {
        User user = (User) AuthFilter.getSession().getAttribute("userInfoFrontend");
        if (user != null) {
            return user.getUserAddress();
        }
        return "";
    }

    @GetMapping("/login.html")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/logout")
    @ResponseBody
    public String logout() {
        AuthFilter.getSession().removeAttribute("userInfoFrontend");
        return "<script>window.location = 'index.html'</script>";
    }
}
